package api

import (
	"service"
	"github.com/gin-gonic/gin"
	"pojo/form"
	"net/http"
	"strconv"
	"pojo/vo"
	"constant"
)

type AdvApi struct {
	service *service.AdvService
}

// 创建AdvApi
func NewAdvApi(service *service.AdvService) *AdvApi {

	return &AdvApi{
		service: service,
	}
}

// 添加广告信息
func (this *AdvApi) Insert(ctx *gin.Context) {

	advInfo := &form.AdvForm{}
	ctx.Bind(advInfo)

	err := this.service.InsertAdv(advInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存广告失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 修改广告信息
func (this *AdvApi) Update(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)
	advInfo := &form.AdvForm{}
	ctx.Bind(advInfo)
	advInfo.Id = id

	err := this.service.UpdateAdv(advInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存广告失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)

}

// 分页查询广告信息
func (this *AdvApi) List(ctx *gin.Context) {
	query := &form.AdvPageQueryForm{}
	ctx.Bind(query)
	result := this.service.QueryAdvs(query)

	ctx.JSON(http.StatusOK, result)
}

// 删除广告信息
func (this *AdvApi) Delete(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	err := this.service.DeleteAdv(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "删除广告失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据ID查询广告信息
func (this *AdvApi) Find(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	adv, err := this.service.FindAdv(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "查询新闻失败"
	} else {
		result = constant.SUCCESS
		result.Info = adv
	}

	ctx.JSON(http.StatusOK, result)
}
